package com.example.cc.client.config;

import com.example.cc.client.initializer.QueueInitializer;
import com.example.cc.client.listeners.ConfigChangeListener;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
public class ClientRabbitConfig {

    private final QueueInitializer queueInitializer;
    private final ConfigChangeListener configChangeListeners;

    // 动态创建客户端队列的方法
    @Bean
    public Queue clientQueue() {
        return queueInitializer.createQueue();
    }

    // 创建绑定
    @Bean
    public Binding clientBinding(Queue clientQueue) {
        return queueInitializer.bindQueueToExchange(clientQueue);
    }

    // 消息监听适配器
    @Bean
    MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(configChangeListeners, "handleChange");
    }

    // 消息监听容器
    @Bean
    public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(clientQueue().getName());
        container.setMessageListener(messageListenerAdapter);
        return container;
    }
}
